import axios from 'axios';
import BASE_CONFIG from './config';
import { Toast } from './function';

interface ApiResponse {
  code: number;
  msg: string;
  data: any;
  timestamp: number;
}

class ApiBase {
  axiosInstance;

  constructor() {
    console.log('Base URL:', BASE_CONFIG.BASE_URL);  // 确认基础 URL
    this.axiosInstance = axios.create({
      baseURL: BASE_CONFIG.BASE_URL,
      timeout: 10000, // 设置请求超时时间
      adapter: this.uniAppAdapter // 使用自定义适配器
    });

    // 添加请求拦截器，在请求头中加入 token
    this.axiosInstance.interceptors.request.use(
      config => {
        const token = uni.getStorageSync('TOKEN');
        if (token) {
          config.headers = {
            ...config.headers,
            'Authorization': token
          };
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.axiosInstance.interceptors.response.use(
      response => {
        const res = response.data as ApiResponse;
        
        // 判断返回的 code
        if (res.code === 200) {
          return res.data; // 直接返回 data 内容
        } else {
          // 非 200 状态码显示错误信息
          Toast(res.msg || '请求失败');
          return Promise.reject(new Error(res.msg || '请求失败'));
        }
      },
      error => {
        // 处理请求错误
        const message = error.message || '网络请求失败';
        Toast(message);
        return Promise.reject(error);
      }
    );
  }

  uniAppAdapter(config) {
    return new Promise((resolve, reject) => {
      const { method, url, data, params, headers } = config;
      uni.request({
        method: method.toUpperCase(),
        url: config.baseURL + url,  // 确保 URL 完整
        data: method === 'get' ? params : data,
        header: headers || {}, // 确保 headers 存在
        success: (res) => {
          resolve({
            data: res.data,
            status: res.statusCode,
            statusText: 'OK',
            headers: res.header,
            config,
            request: res
          });
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  get(url, params = {}) {

    return this.axiosInstance.get(url, { params });
  }

  post(url, data = {}) {
    return this.axiosInstance.post(url, data);
  }

  put(url, data = {}) {
    return this.axiosInstance.put(url, data);
  }

  delete(url, data = {}) {
    return this.axiosInstance.delete(url, { data });
  }
}

export default new ApiBase(); 